<?php

  define("ROOT", dirname(__FILE__) . "/../");
  
  
  function loadXML($xml_file,$key,$fields){
    $doc = new DOMDocument();
    $doc->load( ROOT.$xml_file);
    //echo ROOT.$xml_file;
    
    $data = array();
    
    $books = $doc->getElementsByTagName($key);
    foreach( $books as $book ){
      $node = array();
      foreach($fields as $field){
        $authors = $book->getElementsByTagName($field );
        $node[$field] = $authors->item(0)->nodeValue;
      }
      array_push($data,$node);
      $node = null;
    }
    return $data;
  }
  
  
  function xCopy($source, $destination, $child=null){
    //用法：

    // xCopy(“feiy”,”feiy2″,1):拷贝feiy下的文件到 feiy2,包括子目录

    // xCopy(“feiy”,”feiy2″,0):拷贝feiy下的文件到 feiy2,不包括子目录

    //参数说明：

    // $source:源目录名

    // $destination:目的目录名

    // $child:复制时，是不是包含的子目录

    if(!is_dir($source)){
        echo "source is not dir";exit;
        return 0;
    }

    if(!is_dir($destination)){
        mkdir($destination, 0777);
    }

    $handle=dir($source);

    while($entry=$handle->read()) {
        if(($entry!=".")&&($entry!="..")){
            if(is_dir($source."/".$entry)){
                if($child)
                xCopy($source."/".$entry,$destination."/".$entry,$child);
            }
            else{
                copy($source."/".$entry,$destination."/".$entry);
              //echo $source."/".$entry.$destination."/".$entry;exit;
            }
        }
    }
    return true;
  }
  
  // file operation
  function create_folders($path) {  
    if (!file_exists($path)) {  
        create_folders(dirname($path));
        mkdir($path, 0755);
    }  
  }  

  function create_file($filename,$content)  {
    //echo "create file $filename \n";
    create_folders(dirname($filename));
    //echo dirname($filename);
    //file_put_contents($filename,$content); 
    $file = fopen($filename,"w");
    fwrite($file,$content);
    fclose($file);    
  }  
  function addto_file($filename,$content)  {
    //echo "addto file $filename \n";
    create_folders(dirname($filename));
    //echo dirname($filename);
    //file_put_contents($filename,$content); 
    $file = fopen($filename,"a");
    fwrite($file,$content);
    fclose($file);    
  }  
  
  //redirect
  function jump($path,$mes="",$sec=0){
    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
    echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"$sec; URL=$path\">";
    echo htmlspecialchars($mes, ENT_QUOTES);
    exit;
  }

  function to_path($a){
    $a=preg_replace('/\n|\r/','',$a); 
    header("Location: $a");  
    exit;
  }


  //template
  /*$smarty->assign('name', 'Ned');
    $smarty->display('tmpl/index.html');
  http://www.smarty.net/docs/en/
  */
  function get_tpl_engine(){
    require_once('lib/Smarty/Smarty.class.php');
    $smarty = new Smarty();
    
    $smarty->setTemplateDir('tmp/smarty/templates');
    $smarty->setCompileDir('tmp/smarty/templates_c');
    $smarty->setCacheDir('tmp/smarty/cache');
    $smarty->setConfigDir('tmp/smarty/configs');
    return $smarty;
  }
  
  function assign_hash($smarty,$hash){
    require_once(ROOT . 'lib/Smarty/Smarty.class.php');
    //$smarty=(Smarty)$smarty;
    foreach((array)$hash as $i=>$j){
      $smarty->assign($i, $j);
    }
  }
  
  
  //db
  /*$db= get_db("classes");
  
  $db->save(array(
  "name"=>"111",
  "room"=>"315"
  ));*/
  function get_db($table){
      require_once(ROOT . "lib/Table.php");
     return new Table($table);
  }
  
  
  /*
  $db = get_filedb("wiki");
  $db->save(array("title"=>"a","content"=>"b")); */
  function get_filedb($file){
    require_once(ROOT . "lib/DB/FILEDB.php");
    return new FILEDB($file);
  }
  
  /*$db = get_sqlitedb("data/test.sqlite","blog");*/
  function get_sqlitedb($path,$table){
    require_once(ROOT . "lib/SqliteAccess.php");
    return new SqliteAccess($path,$table);
  }


  /* 
  $mail = get_mailer();
  $mail -> addTo("@hotmail.com");
  $mail -> addTo("@gmail.com");
  $mail -> setFrom("@gmail.com");
  $mail -> setTitle("中文title");
  $mail -> setBody("中文body");
  $mail -> send(); */
  function get_mailer()
  {
    require_once(ROOT . "lib/Mail.php");
    return new Mail();
  }

  function html_header($charset="utf-8"){
    echo "<meta http-equiv=\"content-type\" content=\"text/html;charset=$charset\"/><title>  </title>";
    echo "<meta name=\"viewport\"    content=\"width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;\"/>";
  }
  
  function download($file){
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=".e(basename($file)));
    header("Content-Description: File Transfer");
    @readfile(ROOT."$file");
    exit;
  }
  function download_str($str,$filename){
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Description: File Transfer");
    echo $str;
    exit;
  }
  
  function get_identify(){
    $ip = get_ip();
    $device = get_device();
    $pos = strripos ($ip, '.');
    return $device."". substr($ip,$pos+1);
  }
  
  function get_ip() { 
    if (! empty ( $_SERVER ["HTTP_CLIENT_IP"] )) { 
      $cip = $_SERVER ["HTTP_CLIENT_IP"]; 
    } else if (! empty ( $_SERVER ["HTTP_X_FORWARDED_FOR"] )) { 
      $cip = $_SERVER ["HTTP_X_FORWARDED_FOR"]; 
    } else if (! empty ( $_SERVER ["REMOTE_ADDR"] )) { 
      $cip = $_SERVER ["REMOTE_ADDR"]; 
    } else { 
      $cip = ''; 
    }
    return $cip;
  }
  
  function get_device(){
    if((bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad')){
        return 'iPad';
    }
    if((bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPhone')){
      return 'iPhone';
    }
    if((bool) strpos($_SERVER['HTTP_USER_AGENT'],'Chrome')){
      return 'Chrome';
    }
    if((bool) strpos($_SERVER['HTTP_USER_AGENT'],'Firefox')){
      return 'Firefox';
    }
    if((bool) strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')){
      return 'IE';
    }
    if((bool) strpos($_SERVER['HTTP_USER_AGENT'],'Xoom')){
      return 'Xoom';
    } 
    
    return $_SERVER['HTTP_USER_AGENT'];
  }
  
  function password($name, $pass = "GAGA"){
  	$loginname = "login_$name";
    $kouling=md5($loginname.$pass);
    
  	if(param('logout') == "true"){
    	setcookie("cookie[$loginname]", "",time()-1,'/');
    	echo "logout";exit;
    }
    
    if ($_COOKIE['cookie'][$loginname] 
    && $_COOKIE['cookie'][$loginname]==$kouling){
    	return;
    }
    if(param('passadmin') == $pass){
    	setcookie("cookie[$loginname]", $kouling,time()+60*60,'/');
    	return;
    }
    
    $htmlsrc = "<h2>Authenticate</h2>
        please input password<br>
        <form method=POST>" . "<input type=password name=passadmin>" . "<input type=submit>" . "</form>";
    echo $htmlsrc;
    exit;
  }
  
  function show404(){
    header("HTTP/1.0 404 Not Found");
    exit;
  }
  function is_post(){
    return $_SERVER["REQUEST_METHOD"] == "POST";
  }
  function param($a){
    return p($a) ? p($a) : g($a);
  }
  function param_int($a){
    return abs(intval(param($a)));
  }
  function param_en($a){
    if(preg_match('/^[\-_0-9a-zA-Z]+$/', param($a))){
      return param($a);
    }else{
      return null;
    }
  }
  function p($a){
    return @ $_POST[$a];
  }
  function g($a){
    return @ $_GET[$a];
  }
  function escape($a){
    return htmlspecialchars($a, ENT_QUOTES);
  }
  
  function code2pic($authstr = "", $width = 60, $height = 25, $space = 10, $size = 5, $line_num = 3, $length = 5){
    $left = 10;
    $top = 2;
    $move = 4;
    $image = imagecreate($width, $height);
    $black = ImageColorAllocate($image, 0, 0, 0);
    $white = ImageColorAllocate($image, 255, 255, 255);
    $gray = ImageColorAllocate($image, 255, 255, 255);
    $silver = ImageColorAllocate($image, 240, 240, 240);
    $msilver = ImageColorAllocate($image, 220, 220, 220);
    $bg_white = ImageColorAllocate($image, 255, 255, 255);
    imagefill($image, 0, 0, $bg_white);
    for ($i = 0; $i < strlen($authstr); $i++){
      $y = ($i % 2) * $move + $top;
      imagestring($image, $size, $space * $i + $left, $y, substr($authstr, $i, 1), $black);
    }
    Header("Content-type: image/PNG");
    ImagePNG($image);
    ImageDestroy($image);
  }
  
  function set_cookie($name, $value, $limit = 86400){
    setcookie($name, $value, time() + $limit, "/");
  }
  
  function get_cookie($name){
    if (isset ($_COOKIE[$name])){
      return $_COOKIE[$name];
    }else{
      return "";
    }
  }
  
  
  
  function getopt_instr($str){
    preg_match_all('/\-([^ \-]+) +([^ \-]+)/', $str, $matches);
    $all = count($matches[1]);
    $return = array ();
    for ($i = 0; $i < $all; $i++){
      $optname = $matches[1][$i];
      $optvalue = $matches[2][$i];
      if (!$return[$optname]){
        $return[$optname] = array ();
      }
      $return[$optname][] = $optvalue;
    }
    return $return;
  }
  
  function daxie2xiaoxie($str){
    $big = explode(",", "０,１,２,３,４,５,６,７,８,９");
    $small = explode(",", "0,1,2,3,4,5,6,7,8,9");
    return str_replace($big, $small, $str);
  }
  
  function microtime_float(){
    list ($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
  }
  
  function findexts($filename){
    $filename = strtolower($filename);
    $exts = split("[/\\.]", $filename);
    $n = count($exts) - 1;
    $exts = $exts[$n];
    return $exts;
  }
  
  function trucate($a, $num = 350){
    $a=preg_replace('/\n|\r/','',$a);
    return mb_convert_encoding(substr($a, 0, $num), "UTF-8", "UTF-8");
  }
  
  function random_str($length = 7, $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz023456789"){
    srand((double) microtime() * 1000000);
    $i = 0;
    $pass = '';
    $lengthstr = strlen($chars);
    while ($i < $length){
      $num = rand() % $lengthstr;
      $tmp = substr($chars, $num, 1);
      $pass = $pass . $tmp;
      $i++;
    }
    return $pass;
  }
  
  function search_file_contents($dir, $key = null, $subdir = ""){
    $files = array ();
    if ($dh = opendir($dir)){
      while (($file = readdir($dh)) !== false){
        if (preg_match('/^\./', $file)){
          continue;
        }
        if (is_dir($dir . $file)){
          if ($subdir){
            $files = array_merge($files, search_file_contents($dir . $file.'/', $key, $subdir . $file . "/"));
          }else{
            $files = array_merge($files, search_file_contents($dir . $file.'/', $key, $file . "/"));
          }
        }elseif (strstr(file_get_contents($dir . $file),$key)){
          if ($subdir){
            $files[] = $subdir . $file;
          }else{
            $files[] = $file;
          }
        }
      }
      closedir($dh);
    }
    
    return $files;
  }
  
  function search_dir($dir, $key = null, $subdir = ""){
    $files = array ();
    if ($dh = opendir($dir)){
      while (($file = readdir($dh)) !== false){
        if (preg_match('/^\./', $file)){
          continue;
        }
        if (is_dir($dir . $file)){
          if ($subdir){
            $files = array_merge($files, search_dir($dir . $file, $key, $subdir . "/" . $file . "/"));
          }else{
            $files = array_merge($files, search_dir($dir . $file, $key, $file . "/"));
          }
        }elseif (preg_match('/' . $key . '/', $file)){
          if ($subdir){
            $files[] = $subdir . $file;
          }else{
            $files[] = $file;
          }
        }
      }
      closedir($dh);
    }
    return $files;
  }
  
  function sortfiles($dir,$files){
    $forsort = array();
    foreach($files as $one){
      $forsort[$one] = filectime($dir.$one);
    }
    asort($forsort);
    $result = array();
    foreach ($forsort as $key => $val) {
      array_push($result,$key);
    }
    return array_reverse($result);
  }
  
  function pagefooter($page_base_url, $page, $total, $pagesize = 10,$window_size=9){
    $page = intval($page);
    
    if (!$total)
      return "";
    $pages = ceil($total / $pagesize);
    
    if ($page < 1)
      $page = 1;
    if ($page > $pages)
      $page = $pages;
    
    $offset = $pagesize * ($page -1);
    
    $init = 1;
    $max = $pages;
    $pagelen = ($window_size % 2) ? $window_size : $window_size + 1; //7->7 8->9
    $pageoffset = ($pagelen -1) / 2; // 7->3 9->4
    
    $pagecode = ''; 
   
    if ($page != 1){
      $pagecode .= "<a href='{$page_base_url}&page=1'>&nbsp;<<&nbsp;</a>$end";
      //$pagecode .= "<a href='{$page_base_url}&page=" . ($page -1) . "'>&nbsp;&lt&nbsp;</a>$end";
    }
    
    if ($pages > $pagelen){
      if ($page <= $pageoffset){
        $init = 1;
        $max = $pagelen;
      }else{
        if ($page + $pageoffset >= $pages + 1){
          $init = $pages - $pagelen + 1;
        }else{
          $init = $page - $pageoffset;
          $max = $page + $pageoffset;
        }
      }
    }
    
    for ($i = $init; $i <= $max; $i++){
      if ($i == $page){
        $pagecode .= '<span>&nbsp;' . sprintf("%02d", $i) . '&nbsp;</span>' . $end;
      }else{
        $pagecode .= "<a href='{$page_base_url}&page=$i'>&nbsp;" . sprintf("%02d", $i) . "&nbsp;</a>$end";
      }
    }
    if ($page != $pages){
      //$pagecode .= "<a href='{$page_base_url}&page=" . ($page + 1) . "'>&nbsp;&gt;&nbsp;</a>$end";
      $pagecode .= "<a href='{$page_base_url}&page=$pages'>&nbsp;&gt;&gt;&nbsp;</a>";
    }

    return $pagecode;
}


?>